<template>
  <div class="dashboard-container">
    <h2>{{ type === "add" ? "新增用户" : "修改用户信息" }}</h2>
    <div class="dashboard-text">
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        label-width="150px"
        class="demo-ruleForm"
      >
        <el-form-item label="头像：" prop="avatar">
          <el-avatar :src="ruleForm.avatar" />
        </el-form-item>

        <el-form-item label="用户名：" prop="username">
          <el-input
            v-model="ruleForm.username"
            placeholder="请输入用户名"
            maxlength="10"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="手机号码：" prop="phone">
          <el-input
            v-model="ruleForm.phone"
            placeholder="请输入手机号码"
            maxlength="11"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="密码：" prop="password">
          <el-input
            v-model="ruleForm.password"
            placeholder="请输入身份证号码"
            maxlength="18"
            show-word-limit
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSaveContent">保存</el-button>
          <el-button @click="$router.back()">返回</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div v-if="type !== 'add'" class="disabled-table">
      <h2>查看档案</h2>
      <el-table
        :data="tableData"
        border
        style="width: 100%"
        :header-cell-style="{ background: '#f5f5f5' }"
      >
        <el-table-column label="身高（cm）" prop="height" />
        <el-table-column label="体重（kg）" prop="weight" />
        <el-table-column label="血压（MmHg）" prop="blood_pressure" />
        <el-table-column label="血糖（mg/dL）" prop="blood_sugar" />
        <el-table-column label="脉搏（次/分）" prop="pulse" />
        <el-table-column label="心率（Bpm）" prop="heart_rate" />
        <el-table-column label="卡路里（千卡）" prop="calorie" />
        <el-table-column label="创建时间" prop="create_time" />
        <el-table-column label="更新时间" prop="update_time" />
        <el-table-column label="操作" prop="op">
          <template slot-scope="scope">
            <el-button
              type="danger"
              @click="handleDel(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <Pagination
        :page-sizes="paginationConfig.pageSizes"
        :layout="paginationConfig.layout"
        :total="paginationConfig.total"
        :page="paginationConfig.page"
        :limit="paginationConfig.pageSize"
        @pagination="handleChangePage"
      />
    </div>
  </div>
</template>

<script>
import {
  createUserDetail,
  deleteUser,
  getUserDetail,
  updateUserDetail
} from '@/api/user'
import {
  delHealthRecordsDetail,
  getHealthRecordsList
} from '@/api/health_records'
export default {
  name: 'Dashboard',
  components: {},
  data() {
    return {
      ruleForm: {
        phone: '',
        password: '',
        avatar: '',
        username: ''
      },
      contentId: null,
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        phone: [{ required: true, message: '请输入手机号码', trigger: 'blur' }],
        password: [
          { required: true, message: '请输入手机号码', trigger: 'blur' }
        ]
      },
      tableData: [],
      paginationConfig: {
        direction: 'center', // 分页位置
        layout: 'total, sizes, prev, pager, next, jumper', // 分页类型
        pageSizes: [10, 20], // 分页pages
        total: 0,
        page: 1, // 页数-默认1
        pageSize: 10 // 每页条数-默认10
      }
    }
  },
  computed: {
    type() {
      return this.$route.query.type
    }
  },
  created() {
    this.handleGetUserDetail()
    this.handleGetHealthRecordsList()
  },
  methods: {
    async handleGetUserDetail() {
      if (!this.$route.query.id) return
      const res = await getUserDetail({
        id: this.$route.query.id
      })
      if (res.code === 200) {
        this.ruleForm = Object.assign({}, res.data)
      }
    },
    async handleGetHealthRecordsList() {
      if (!this.$route.query.id) return
      const { page, pageSize } = this.paginationConfig
      const res = await getHealthRecordsList({
        userId: this.$route.query.id,
        page,
        pageSize
      })
      if (res.code === 200) {
        this.tableData = res.data.list
        this.total = res.data.total
      }
    },
    handleChangePage({ page, pageSize }) {
      this.paginationConfig.page = page
      this.paginationConfig.pageSize = pageSize
      this.handleGetHealthRecordsList()
    },
    handleSaveContent() {
      this.$confirm(
        `此操作将影响用户：${this.ruleForm.username}的登录, 是否继续?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async() => {
        this.$refs.ruleForm.validate(async(valid) => {
          console.log(valid)
          if (valid) {
            const api =
              this.type === 'add' ? createUserDetail : updateUserDetail
            const res = await api({
              ...this.ruleForm
            })
            if (res.data && res.code === 200) {
              this.$message.success(
                `${this.type === 'add' ? '新建' : '保存'}成功`
              )
              this.$router.back()
            }
          }
        })
      })
    },
    async handleDel(e) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const res = await delHealthRecordsDetail({
          id: e.id
        })
        if (res.code === 200) {
          this.$message.success(res.data)
          this.handleGetHealthRecordsList()
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.dashboard {
  &-container {
    margin: 30px;
  }
  &-text {
    margin-bottom: 30px;
  }
}
</style>
